/*
 * DeliveryFacadeBean.java
 *
 * Created on 8 May 2007, 11:31
 * Copyright (C) 2007   Yuezhong Zhang
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package usyd.comp5348;

import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Yuezhong Zhang
 */
@Stateless(mappedName="ejb/Delivery")
public class DeliveryFacadeBean implements DeliveryFacadeRemote, DeliveryFacadeLocal {

    @EJB
    private OrderFacadeRemote orderRemote;
    
    @EJB(mappedName="ejb/Stock")
    private StockFacadeRemote stockFacadeBean;
    
    private Logger logger = Logger.getLogger("usyd.comp5348.DeliveryFacadeBean");
    
    @PersistenceContext
    private EntityManager em;
    
    private boolean isRPCEnabled = false;
    /** Creates a new instance of DeliveryFacadeBean */
    public DeliveryFacadeBean() {
    }
    /**
     *Create a delivery
     *@param delivery  an instance of delivery info, cannot be null
     *@return id the id of new delivery
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public int createDelivery(Delivery delivery) {
        em.persist(delivery);
        em.flush();
        return delivery.getId();
    }
    /**
     * Modiy an exisiting delivery
     *@param delivery  the new informaiton about delivery
     *@throw deliveryException  if delivery not found
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void modifyDelivery(Delivery delivery) throws DeliveryException {
        Delivery  de = em.find(Delivery.class,delivery.getId());
        if(de == null) {
            DeliveryException dex = new DeliveryException("Couldn't find delivery with id="+ delivery.getId());
            logger.warning(dex.getMessage());
            throw dex;
        }
        de.setOrderId(delivery.getOrderId());
        de.setStatus(delivery.getStatus());
        de.setWarehouse(delivery.getWarehouse());
        de.setDeliveryDate(delivery.getDeliveryDate());
        em.merge(de);
        em.flush();
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void deleteDelivery(int id) {
        Delivery  de = em.find(Delivery.class,id);
        if(de !=null){
            em.remove(de);
            em.flush();
        }
    }
    @Deprecated
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void submitDelivery(int id) throws DeliveryException {
        throw new DeliveryException("This method is no longer supported");
        //This is requried in JMS
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void submitDelivery(Delivery d, Order order)throws DeliveryException{
        Delivery del = getDeliveryById(d.getId());
        if(del.getOrderId() != order.getId()){
            throw new DeliveryException("Delivery and order id doesn't match");
        }
        try {
            for(OrderLine ol : order.getVideos()) {
                stockFacadeBean.sold(ol.getCatalogueId(),ol.getQuantity(),order.getWarehouse());
            }
        } catch (StockException ex) {
            ex.printStackTrace();
            throw new DeliveryException("Failed to submit delivery");
        }
        if (isRPCEnabled){
            try {
                //
                orderRemote.updateOrderStatus(order.getId(),Order.DELIVERED);
            } catch (OrderException ex) {
                ex.printStackTrace();
            }
        }
    }
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public Delivery getDeliveryById(int id) {
        return em.find(Delivery.class,id);
    }
    
}
